import { message, Spin } from 'antd';
import React, { useContext, useEffect, useState } from 'react'
import { reqAddCourse, reqCourseList, reqSearchCou, updateCourse } from '@/api/api';
import { Context } from '@/App';
import useAdditionalInfor from '@/hooks/useAdditionalInfor';
import { useRestrictedCurriculums } from '@/hooks/useRestrictedCurriculums';
import { updateSearchInfor } from '@/tool/updateSearchInfor';
import './course.less'

import CourseSearch from '@/components/CourseUI/CourseSearch';
import CourseTable from '@/components/CourseUI/CourseTable';
import AddCourse from '@/components/CourseUI/AddCourse';

export default function Course() {
  const [courseCell, setCourseCell] = useState()
  const [loading, setLoading] = useState(true)
  const [openForm, setOpenForm] = useState(false)

  const [collInfor, setCollInfor] = useState()
  const [searchInfor, setSearchInfor] = useState({ 'fd_week': 1, 'fd_semester': 1 })

  const { role } = useContext(Context)
  const { classes, teacher, allCurriculunms, classroom } = useAdditionalInfor(role)
  const { curriculums} =useRestrictedCurriculums(role,searchInfor.fd_semester)
  
  const additionalInfor = { classes, teacher, allCurriculunms, classroom }

  useEffect(() => {
    if (role !== null) {
      getCourseList(role)
    }
  }, [role])

  //获取课表数据
  const getCourseList = (role) => {
    setLoading(true)
    reqCourseList({ ...role, ...searchInfor }).then(
      res => {
        setLoading(false)
        if (res.status === 200) {
          setCourseCell(getNewCell(fillCell(res.data)))
        }else if(res.status === 201){
          setCourseCell(getNewCell(fillCell([])))
        }
      },
    )
  }

  // 课表数据规则排序
  const getNewCell = (courseList) => {
    let one = courseList.filter((item) => item.fd_section === 1).sort((a, b) => a.fd_day - b.fd_day)
    let two = courseList.filter((item) => item.fd_section === 2).sort((a, b) => a.fd_day - b.fd_day)
    let three = courseList.filter((item) => item.fd_section === 3).sort((a, b) => a.fd_day - b.fd_day)
    let four = courseList.filter((item) => item.fd_section === 4).sort((a, b) => a.fd_day - b.fd_day)
    let five = courseList.filter((item) => item.fd_section === 5).sort((a, b) => a.fd_day - b.fd_day)
    let six = courseList.filter((item) => item.fd_section === 6).sort((a, b) => a.fd_day - b.fd_day)
    let seven = courseList.filter((item) => item.fd_section === 7).sort((a, b) => a.fd_day - b.fd_day)
    let eight = courseList.filter((item) => item.fd_section === 8).sort((a, b) => a.fd_day - b.fd_day)
    let nine = courseList.filter((item) => item.fd_section === 9).sort((a, b) => a.fd_day - b.fd_day)
    let ten = courseList.filter((item) => item.fd_section === 10).sort((a, b) => a.fd_day - b.fd_day)
    let data = [...one, ...two, ...three, ...four, ...five, ...six, ...seven, ...eight, ...nine, ...ten]
    return data
  }

  // 数据库查询不足一周数据时补充（70）
  const fillCell = (data, searchData) => {
    const start = data.length
    if (data.length < 70) {
      for (let i = 1; i <= 10; i++) {
        for (let j = 1; j <= 7; j++) {
          let a = {
            fd_teacNum: role.fd_idNum,
            fd_week: !searchData ? searchInfor.fd_week : searchData.fd_week,
            fd_section: "",
            fd_day: ""
          }
          data.map((item) => {
            if (item.fd_day === j && item.fd_section === i) {
              return a = { ...item, ...a }
            }
          })
          a.fd_section = i;
          a.fd_day = j;
          data = [...data, a]
          continue
        }
        continue
      }
      return data.splice(start, data.length)
    } else {
      return data
    }
  }

  // 搜索
  const onSearchFinish = (data) => {
    const searchData =updateSearchInfor(data)
    setSearchInfor(searchData)
    reqSearchCou({ role, searchData }).then(
      res => {
        if (res.status === 200) {
          setCourseCell(getNewCell(fillCell(res.data, searchData)))
        }
        if (res.status === 201) {
          setCourseCell(getNewCell(fillCell([], searchData)))
          // getCourseList(role)
        }
      }
    )
  };

  // 重置
  const Reset = () => {
    setLoading(true)
    reqCourseList({ ...role, fd_week: 1, fd_semester: 1 }).then(
      res => {
        setLoading(false)
        if (res.status === 200) {
          setCourseCell(getNewCell(fillCell(res.data)))
        }else if(res.status === 201){
            
        }
      },
    )
  }

  // 单元格信息
  const getCellInfor = (event) => {
    setOpenForm(true);
    setCollInfor(event)
  }

  // 表单提交
  const formSubmit = (data) => {
    console.log("表单数据", data);
    if ("fd_id" in data) {
      updateCourse(data).then(
        res => {
          if(res.status === 200){
            message.success("修改成功")
          }
          if(res.status === 201){
            message.error("修改失败")
          }
          setOpenForm(false)
          onSearchFinish(searchInfor)
        }
      )
    }
    if(!("fd_id" in data)){
      // 添加提交
      reqAddCourse({data,fd_semester:searchInfor.fd_semester}).then(
        res => {
          if (res.status === 200) {
            console.log("成功");
            message.success(res.data)
          }
          if(res.status === 201){
            message.error(res.data?res.data:"添加失败")
          }
          setOpenForm(false)
          onSearchFinish(searchInfor)
        }
      )
    }
  }

  return (
    <div className='course-box'>
      {
        loading ? <Spin size='large' className='loading' /> :
          <>
            <div className='curse-select'>
              <CourseSearch
                onFinish={onSearchFinish}
                Reset={Reset}
                role={role}
                classes={classes}
              />
            </div>
            <div className='course-table'>
              <CourseTable getCellInfor={getCellInfor} courseCell={courseCell} />
            </div>
            <AddCourse
            curriculums={curriculums}
              additionalInfor={additionalInfor}
              searchInfor={searchInfor}
              role={role}
              collInfor={collInfor}
              open={openForm}
              onCreate={formSubmit}
              onCancel={() => {
                setOpenForm(false);
                setCollInfor(null)
              }}
            />
          </>
      }
    </div>
  )
}
